import { FC, PropsWithChildren, MutableRefObject, useRef, useEffect } from 'react'
import { Button, message } from 'antd'
import {
  ModalForm,
  ProFormText,
} from '@ant-design/pro-form'
import { ActionType } from '@ant-design/pro-table'
import type { ProFormInstance } from '@ant-design/pro-form'
import { ModelFormModeEnum } from '@/enums/ModelFormModeEnum'
import { environmentSave, environmentUpdate } from '@/api/efficient/environment'
import { EnvironmentDTO } from '@/model/efficient/EnvironmentDTO'

interface EnvironmentFormParam {
  mode: ModelFormModeEnum,
  row?: EnvironmentDTO,
  actionRef: MutableRefObject<ActionType>
}

const EnvironmentForm: FC<EnvironmentFormParam> = (props: PropsWithChildren<EnvironmentFormParam>) => {
  const { mode, row, actionRef } = props
  const formRef = useRef<ProFormInstance>()
  useEffect(() => {
    formRef.current?.setFieldsValue(row)
  }, [row])

  const formItemLayout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 14 },
  }
  return (
    <div className="environment-form">
      <ModalForm<EnvironmentDTO>
        formRef={formRef}
        title={ModelFormModeEnum.add === mode ? '新增' : '编辑'}
        trigger={
          <Button type={ModelFormModeEnum.add === mode ? 'primary' : 'link'}>
            {ModelFormModeEnum.add === mode ? '新增' : '编辑'}
          </Button>
        }
        layout="horizontal"
        {...formItemLayout}
        onFinish={async (values) => {
          if (mode === ModelFormModeEnum.add) await environmentSave(values)
          else if (mode === ModelFormModeEnum.update) await environmentUpdate(values)
          message.success(`${ModelFormModeEnum.add === mode ? '新增' : '编辑'}成功`)
          formRef?.current?.resetFields()
          await actionRef.current.reload()
          return true
        }}
      >
        <ProFormText
          name="id"
          label="id"
          placeholder="id"
          hidden
        />
        <ProFormText
          name="code"
          label="环境code"
          placeholder="环境code"
        />
        <ProFormText
          name="name"
          label="环境名称"
          placeholder="服务器内网ip"
        />
        <ProFormText
          name="principal"
          label="负责人"
          placeholder="请输入负责人"
          rules={[{ required: true, message: '请输入负责人' }]}
        />
      </ModalForm>
    </div>
  )
}

export default EnvironmentForm
